/*
 * @Author: 姚沈阳 11500793+yao-shenyang@user.noreply.gitee.com
 * @Date: 2023-10-19 11:18:57
 * @LastEditors: 姚沈阳 11500793+yao-shenyang@user.noreply.gitee.com
 * @LastEditTime: 2023-10-20 20:27:51
 * @FilePath: \uni-preset-vue-vite-ts\uniCloud-aliyun\cloudfunctions\userset\index.js
 * @Description: 
 * qq1908552310
 */
'use strict';
const jwt = require('jsonwebtoken');
exports.main = async (event, context) => {
	//event为客户端上传的参数
	console.log('event : ', event)

	const {
		type,
		username,
		password
	} = event
	let result = null
	try {
		const db = uniCloud.database()
		const userCollection = db.collection('users')
		if (type === 'login') {
			// 登录操作
			result = await userCollection.where({
				username,
			}).get()
			// 用户不存在，返回错误
			if (result.data.length == 0) {
				return {
					code: -1,
					message: '用户不存在'
				};
			}
			// 密码不匹配，返回错误
			if (result.data[0].password !== password) {
				return {
					code: -1,
					message: '密码错误'
				};
			}
			// 生成 token
			const token = jwt.sign({ userId: result.data[0]._id }, 'your-secret-key', { expiresIn: '1h' });

			return {
				code: 0,
				username,
				message: '登录成功',
				token
			};
		} else if (type === 'register') {
			// 注册操作
			result = await userCollection.add({
				data: {
					username,
					password
				}
			})
			return result
		}
		// //返回数据给客户端
		// return result
	} catch (err) {
		return {
			code: -1,
			message: '登录失败'
		};
	}
};